package com.yun2.bms.controller.user;

import com.yun2.bms.model.Category;
import com.yun2.bms.model.User;
import com.yun2.bms.service.IUserService;
import com.yun2.bms.service.impl.UserServiceImpl;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/6/4
 */

public class UserController implements Initializable {

    private IUserService userService = new UserServiceImpl();

    //存放数据库查询出来的数据列表
    private List<User> userList = null;

    //用户模型数据集合，可以实时相应数据变化，无需刷新
    private ObservableList<User> userData = FXCollections.observableArrayList();

    @FXML
    private TableColumn<User, User> role;

    @FXML
    private TableColumn<User, User> gender;

    @FXML
    private Button btnEdit;

    @FXML
    private TextField tfUserInfo;

    @FXML
    private Button btnQuery;

    @FXML
    private TableColumn<User, User> userName;

    @FXML
    private Button btnDelete;

    @FXML
    private Pagination pager;

    @FXML
    private Button btnAdd;

    @FXML
    private TableColumn<User, User> phone;

    @FXML
    private TableColumn<User, User> loginName;

    @FXML
    private TableView<User> userTable;

    @FXML
    private TableColumn<User, User> id;

    @FXML
    private Button btnReset;

    @FXML
    private TableColumn<User, User> email;

    @FXML
    void add(ActionEvent event) throws IOException {
        addNewUser();
        clearSelection();
    }

    @FXML
    void edit(ActionEvent event) throws IOException {
        this.editUser();
        clearSelection();
    }

    @FXML
    void delete(ActionEvent event) {
        this.deleteUsers();
        clearSelection();
    }

    @FXML
    void query(ActionEvent event) {
        //获取查询数据
        String userInfo = this.tfUserInfo.getText();
        if (StringUtils.isNotBlank(userInfo)) {
            List<User> list = this.userService.getAllByUserInfo(userInfo);
            this.userData.clear();
            this.userData.addAll(list);
            this.userTable.setItems(userData);
        }
    }

    @FXML
    void reset(ActionEvent event) {
        this.userData.clear();
        //初始化表格
        this.tfUserInfo.setText("");
        initTable();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //设置数据表多选模式
        this.userTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        //设置数据表行双击事件
        this.userTable.setRowFactory(tv -> {
            TableRow<User> row = new TableRow<User>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (!row.isEmpty())) {
                    try {
                        editUser();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            return row;
        });
        //初始化数据表格
        initTable();
        //初始化按钮
        initButtons();
    }

    /**
     * 初始化数据表格
     */
    private void initTable() {
        this.userList = this.userService.getAll();
        this.userData.addAll(userList);
        this.userTable.setItems(userData);
    }

    /**
     * 清空tableview选择
     */
    private void clearSelection() {
        this.userTable.getSelectionModel().clearSelection();
        //初始化按钮
        initButtons();
    }
    /**
     * 初始化按钮
     */
    private void initButtons() {
        //默认打开表格时，没有数据被选中
        this.btnDelete.setDisable(true);
        this.btnEdit.setDisable(true);
        //初始化按钮状态
        this.userTable.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            int number = this.userTable.getSelectionModel().getSelectedItems().size();
            if (number == 1) {
                this.btnEdit.setDisable(false);
                this.btnDelete.setDisable(false);
            }
            if (number > 1) {
                this.btnEdit.setDisable(true);
                this.btnDelete.setDisable(false);
            }
        });
    }

    /**
     * 打开添加数据窗口
     * @throws IOException
     */
    private void addNewUser() throws IOException {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        //读入布局
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/user/addUser.fxml"));
        //创建一个与main.fxml根布局元素相同类型的布局对象root
        Parent root = fxmlLoader.load();
        AddUserController addUserController = fxmlLoader.getController();
        addUserController.setUserData(this.userData);
        Scene scene = new Scene(root);
        stage.setTitle("图书管理系统-添加图书");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    /**
     * 打开编辑数据窗口
     * @throws IOException
     */
    private void editUser() throws IOException {
        User user = this.userTable.getSelectionModel().getSelectedItem();
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        //读入布局
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/user/editUser.fxml"));
        //创建一个与main.fxml根布局元素相同类型的布局对象root
        Parent root = fxmlLoader.load();
        EditUserController editUserController = fxmlLoader.getController();
        editUserController.setUser(user);
        Scene scene = new Scene(root);
        stage.setTitle("图书管理系统-编辑图书");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    /**
     * 删除用户
     */
    private void deleteUsers() {
        Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "是否删除选中的数据?");
        confirmation.setHeaderText("提示信息");
        confirmation.showAndWait();
        String info = "";
        if (confirmation.getResult().getButtonData().isDefaultButton()) {
            List<User> list = this.userTable.getSelectionModel().getSelectedItems();
            int ret = userService.delete(list);
            this.userData.removeAll(list);
            if (ret > 0) {
                info = "删除用户成功！";
            } else {
                info = "删除用户失败！";
            }
            //显示提示信息
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示信息");
            alert.setHeaderText(info);
            alert.showAndWait();
        }
    }
}
